<template>
  <div class="main-menu">
    <div class="logo">
      <img class="img" src="@/assets/img/logo.svg" alt="" />
      <h2 v-show="!isFold" class="title">后台管理系统</h2>
    </div>
    <!-- 侧边栏菜单  组的名字
    :collapse="true"折叠-->
    <el-menu
      :collapse="isFold"
      :default-active="defaultActive"
      text-color="#b7bdc3"
      active-text-color="#fff"
      background-color="#001529"
    >
      <!-- 遍历整个菜单 -->
      <template v-for="item in userMenus" :key="item.id">
        <!-- 一级菜单 el-sub-menu可嵌套-->
        <el-sub-menu :index="item.id + ''">
          <template #title>
            <!-- <i class=""></i> -->
            <!-- <i>{{ item.icon }}</i> -->
            <!-- 动态组件 处理图标 -->
            <el-icon><component :is="item.icon.split('-icon-')[1]" /></el-icon>
            <span>{{ item.name }}</span>
          </template>
          <template v-for="subitem in item.children" :key="subitem.id">
            <!-- 菜单项  -->
            <el-menu-item
              @click="handleItemClick(subitem)"
              v-show="!isFold"
              :index="subitem.id + ''"
              >{{ subitem.name }}</el-menu-item
            >
          </template>
        </el-sub-menu>
      </template>
    </el-menu>
  </div>
</template>
<script setup lang="ts">
// 获取动态菜单数据
import router from '@/router'
import useLoginStore from '@/store/login/login'
import { mapPathToMenu } from '@/utils/map-menus'
import { computed } from 'vue'
import { useRoute } from 'vue-router'

// 定义props  用到拿到其返回值
defineProps({
  isFold: {
    type: Boolean,
    default: false
  }
})
// 1，获取动态菜单
const LoginStore = useLoginStore()
// pinia中的数据是响应式的
const userMenus = LoginStore.userMenus
// console.log(userMenus)
// 2，监听item点击
function handleItemClick(subitem: any) {
  router.push(subitem.url)
}
// 3，默认选中菜单 定义变量
const route = useRoute()
// console.log(route.path)
// 根据路径匹配选中的菜单。 需要路径 和菜单
// 有抽取啦工具函数   得到id

const defaultActive = computed(() => {
  const pathMenu = mapPathToMenu(route.path, userMenus)
  return pathMenu?.id + ''
})
</script>
<style lang="less" scoped>
.main-menu {
  height: 100%;
  background-color: #001529;
}

.logo {
  display: flex;
  height: 28px;
  padding: 12px 10px 8px 10px;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  overflow: hidden;

  .img {
    height: 100%;
    margin: 0 10px;
  }

  .title {
    font-size: 16px;
    font-weight: 700;
    color: white;
    white-space: nowrap;
  }
}

.el-menu {
  border-right: none;
  user-select: none;
}

.el-sub-menu {
  .el-menu-item {
    padding-left: 50px !important;
    background-color: #0c2135;
  }

  .el-menu-item:hover {
    color: #fff;
  }

  .el-menu-item.is-active {
    background-color: #0a60bd;
  }
}
</style>
